package org.linlinjava.litemall.core.storage;

import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.linlinjava.litemall.core.util.CharUtil;
import org.linlinjava.litemall.core.util.ImageUploadUtil;
import org.linlinjava.litemall.db.domain.LitemallStorage;
import org.linlinjava.litemall.db.service.LitemallStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
/**
 * 提供存储服务类，所有存储服务均由该类对外提供
 */
@Service
public class StorageClientService {

    @Autowired
    private LitemallStorageService litemallStorageService;

    @Autowired
    private FastFileStorageClient storageClient;

    @Value("${fdfs.prefixAddr}")
    private String prefixAddr;
    /**
     * 存储一个文件对象
     */
    public LitemallStorage store(MultipartFile file) throws IOException {
        LitemallStorage storageInfo = new LitemallStorage();
        long contentLength = file.getSize();
        String contentType=file.getContentType();
        String fileName = file.getOriginalFilename();
        String url = ImageUploadUtil.imageUploadByFile(file, storageClient);
        String key = generateKey(url);
        storageInfo.setName(fileName);
        storageInfo.setSize((int) contentLength);
        storageInfo.setType(contentType);
        storageInfo.setKey(key);
        storageInfo.setUrl(prefixAddr+url);
        litemallStorageService.add(storageInfo);
        return storageInfo;
    }

    private String generateKey(String originalFilename) {
        int index = originalFilename.lastIndexOf('.');
        String suffix = originalFilename.substring(index);

        String key = null;
        LitemallStorage storageInfo = null;

        do {
            key = CharUtil.getRandomString(20) + suffix;
            storageInfo = litemallStorageService.findByKey(key);
        }
        while (storageInfo != null);

        return key;
    }

}
